'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	let id = event.id
	let type = event.type
	if (type == 'get_t') { //获取
		return await db.collection('post').where({
			_id: event.id
		}).get()
	} else if (type == "re_msg") { //回复消息
		let res = await db.collection('comment').doc(id).update({
			read: 1
		})
		if (res.updated) { //更新消息成功写数据库
			return await db.collection('re_comment').add({
				id: event.id,
				r_content: event.content,
				avatar: event.atr
			})
		}
	} else if (type == "readall") {
		let res = await db.collection('post').where({
			u_id: id
		}).field({
			'_id': true
		}).get()
		return await Promise.all(res.data.map(async item=>{
			return await db.collection('comment').where({
				t_id:item._id
			}).update({
					read: 1
				})
		}))
		// return await Promise.all(res.data.map(async (item) => {
		// 	// 等待异步操作完成，返回执行结果
		// 	return await db.collection('comment').where({
		// 		t_id: item._id,
		// 		read: 0
		// 	}).update({
		// 		read: 1,
		// 	})
		// }));
	} else { //获取当前用户消息
		let res = await db.collection('post').where({
			u_id: id
		}).field({
			'_id': true
		}).get()
		return await Promise.all(res.data.map(async (item) => {
			// 等待异步操作完成，返回执行结果
			return await db.collection('comment').where({
				t_id: item._id,
				read: 0
			}).get()
		}));
	}

};
